import { NextRequest, NextResponse } from 'next/server';
import { SESSION_COOKIE_NAME } from './lib/types/session';

export const config = {
  matcher: [
    // 排除静态资源和会话API
    '/((?!_next/static|_next/image|favicon.ico|api/session|images|.well-known).*)',
  ],
};

// 提取客户端信息
function extractClientInfo(request: NextRequest) {
  return {
    ipAddress: request.headers.get('x-forwarded-for') || request.headers.get('x-real-ip') || '',
    userAgent: request.headers.get('user-agent') || '',
    referrer: request.headers.get('referer') || '', // 注意：HTTP头中正确拼写是'referer'（只有一个'r'）
    deviceType: getUserDeviceType(request.headers.get('user-agent') || '')
  };
}

// 简单的设备类型检测
function getUserDeviceType(userAgent: string): string {
  if (/mobile/i.test(userAgent)) return 'mobile';
  if (/tablet/i.test(userAgent)) return 'tablet';
  return 'desktop';
}

export async function middleware(request: NextRequest) {
  const { nextUrl, cookies: requestCookies } = request;
  const response = NextResponse.next();

  // 检查是否为预加载请求或静态资源
  const isPrefetch = request.headers.get('purpose')?.includes('prefetch');
  const isStaticRequest = 
    nextUrl.pathname.includes('/_next/') || 
    nextUrl.pathname.includes('/images/') ||
    nextUrl.pathname.includes('.ico');

  // 非关键请求不处理会话
  if (isPrefetch || isStaticRequest) {
    return response;
  }

  // 获取会话ID和VIP参数
  const sessionId = requestCookies.get(SESSION_COOKIE_NAME)?.value;
  const vipParam = nextUrl.searchParams.get('vip');
  const hasVipParam = vipParam !== null;
  const clientInfo = extractClientInfo(request);
  const baseUrl = process.env.__NEXT_PRIVATE_ORIGIN || "";
  
  // 修改：总是调用会话API进行校验，而不只是在没有会话或有VIP参数时
  try {
    const sessionResponse = await fetch(`${baseUrl}/api/session`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        sessionId,
        isVip: vipParam === '1',
        hasVipParam,
        clientInfo,
        validateSession: true, // 添加标记，表示需要校验会话有效性
        path: nextUrl.pathname
      })
    });

    if (sessionResponse.ok) {
      const result = await sessionResponse.json();
      
      if (result.sessionId) {
        // 设置会话cookie
        response.cookies.set(SESSION_COOKIE_NAME, result.sessionId, {
          path: '/',
          httpOnly: true,
          sameSite: 'lax',
          secure: process.env.NODE_ENV === 'production',
          maxAge: 30 * 24 * 60 * 60 // 30天
        });
      }
      
      // 设置VIP头信息便于服务端组件访问
      response.headers.set('x-is-vip', String(result.isVip || false));
    }
  } catch (error) {
    console.error('会话处理失败:', error);
  }

  return response;
} 